<?php
namespace app\store\model\food;

use app\common\model\Record as RecordModel;
use think\facade\Db;

/**
 * 交易记录模型
 */
class Record extends RecordModel
{
     // 追加字段
    protected $append = [
        'shop'
    ];

    /**
     * 类型
     */
    public function getShopAttr($value,$data)
    {
        return Shop::get($data['shop_id']);
    }
    
    /**
     * 充值余额
    */
    public function add(array $data)
    {
    	$user = User::get($data['user_id']);
		if(empty($data["value"])){
			$this->error = '变更金额不可为空';
			return false;
		}
		if(strpos($data["value"],".")){
			$this->error = '变更金额必须为整数';
			return false;
		}
		if(empty($data["shop_id"])){
			$this->error = '请选择门店';
			return false;
		}
		if($data["mode"] == 10){
			$user->money = ['inc',$data["value"]];//增加
		}
		if($data["mode"] == 20){
			$user->money = ['dec',$data["value"]];//扣减
		}
		if($data["mode"] == 30){
			$user->money = $data["value"];//重置
		}
		$data = [
			'mode' => 20, //后台充值
			'type' => 10, //余额
			'action' => $data['mode'],
			'order_no' => order_no(),
			'money' => $data['value'],
			'remark' => $data['remark'],
			'shop_id' => $data['shop_id'],
			'user_id' => $data['user_id'],
			'applet_id' => self::$applet_id
		];
		// 开启事务
        Db::startTrans();
        try {
        	$user->save();
            $this->save($data);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }

}
